package com.gupao.vip.bio;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * 客户端-发送数据
 * @author dell
 *
 */
public class Send implements Runnable {
	/**
	 * 控制台输入流
	 */
	private BufferedReader console;
	
	/**
	 * 管道输出流
	 */
	private DataOutputStream dataOutputStream;
	
	/**
	 * 控制线程
	 */
	private boolean isRunning = true;
	
	public Send(){
		console = new BufferedReader(new InputStreamReader(System.in));
	}
	
	public Send(Socket client, String name){
		this();
		try {
			dataOutputStream = new DataOutputStream(client.getOutputStream());
			sendMsg(name);
		} catch (IOException e) {
			System.err.println(e);
			IOUtils.closeQuietly(dataOutputStream);
			isRunning = false;
		}
	}
	/**
	 * 从控制台接收数据
	 * @return
	 */
	private String getMsgFromConsole(){
		try {
			return console.readLine();
		} catch (IOException e) {
			System.err.println(e);
		}
		return "";
	}
	
	/**
	 * 从控制台接收数据，发送数据
	 * @param msg
	 */
	public void sendMsg(String msg){
		if(StringUtils.isNotEmpty(msg)){
			try {
				dataOutputStream.writeUTF(msg);
				dataOutputStream.flush();
			} catch (IOException e) {
				System.err.println(e);
				IOUtils.closeQuietly(dataOutputStream);
				isRunning = false;
			}
		}
	}
	@Override
	public void run() {
		while(isRunning){
			sendMsg(getMsgFromConsole());
		}
		
	}

}
